<?php
/**
 * Created by PhpStorm.
 * User: xiaoqi
 * Date: 18-9-19
 * Time: 下午2:49
 */

namespace App\HttpController\Api;

use Particle\Validator\Validator;
use App\Model\Permission as PermissionModel;

class Permission extends AbstractBase
{
    /**
     * 定义验证规则，required必须验证,optional传值才验证
     */
    protected function rules($form)
    {
        $validator = new Validator();
        $validator->required('name');
        $validator->required('display_name');
        $validator->required('description');
        return $validator->validate($form);
    }

    /**
     * 添加权限
     */
    public function add()
    {
        $server = $this->request()->getServerParams();
        if ($server['request_method'] !== 'POST') {
            return $this->error('请求方法不允许', 405);
        }

        $posts = $this->request()->getParsedBody();
        $ret = $this->rules([
            'name'          => $posts['name'],
            'display_name'  => $posts['display_name'],
            'description'   => $posts['description']
        ]);
        if (!$ret->isValid()) {
            $error = $this->valideErrorFirst($ret->getMessages());
            return $this->error($error);
        }
        if (PermissionModel::where('name', $posts['name'])) {
            return $this->error('该权限已经存在');
        }

        $user = $this->request()->user;
        $model = new PermissionModel();
        $model->name = $posts['name'];
        $model->display_name = $posts['display_name'];
        $model->description = $posts['description'];
        $model->created_uid = (int)$user->id;
        $ret = $model->save();
        if ($ret) {
            go(function () use ($model, $user) {
                $role = $user->roles[0];
                $model->roles()->attach($role->id);
            });
            return $this->success(true);
        }
        return $this->error('添加失败，请重试');
    }
}